package com.zhangxin.aiInterview.controller;

import cn.hutool.core.bean.BeanUtil;
import com.zhangxin.aiInterview.annotation.AuthCheck;
import com.zhangxin.aiInterview.common.BaseResponse;
import com.zhangxin.aiInterview.common.ErrorCode;
import com.zhangxin.aiInterview.common.ResultUtils;
import com.zhangxin.aiInterview.constant.UserConstant;
import com.zhangxin.aiInterview.exception.BusinessException;
import com.zhangxin.aiInterview.model.dto.exam.ExamGenerateRequest;
import com.zhangxin.aiInterview.model.dto.interview.InterviewGenerateRequest;
import com.zhangxin.aiInterview.model.dto.resume.UploadFileRequest;
import com.zhangxin.aiInterview.model.entity.*;
import com.zhangxin.aiInterview.model.enums.AnalyzeStatusEnum;
import com.zhangxin.aiInterview.model.vo.response.GetFullProcessInterviewAnalyzeResultResponse;
import com.zhangxin.aiInterview.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/full/interview")
@Slf4j
public class FullInterviewController {
    @Resource
    private UserService userService;
    @Resource
    private ExamService examService;
    @Resource
    private ResumeService resumeService;
    @Resource
    private FullProcessInterviewService fullProcessInterviewService;
    @Resource
    private FullProcessAnalyzeResultService fullProcessAnalyzeResultService;
    @Resource
    private PositionService positionService;
    @Resource
    private ResumeAnalysisResultService resumeAnalysisResultService;
    @Resource
    private ExamAnalysisResultService examAnalysisResultService;
    @Resource
    private AiInterviewService aiInterviewService;
    @Resource
    private AiInterviewAnalyzeResultService aiInterviewAnalyzeResultService;
    @Resource
    private HrInterviewService hrInterviewService;
    @Resource
    private HrInterviewAnalyzeResultService hrInterviewAnalyzeResultService;
    @Resource
    private CompanyService companyService;
    @Resource
    private FullProcessInterviewAnalyzeResultService fullProcessInterviewAnalyzeResultService;

    /**
     * 下一步
     *
     * @param fullInterviewId
     * @param step
     * @return
     */
    @GetMapping("/next/step")
    public BaseResponse<Boolean> fullInterviewNextStep(@RequestParam("fullInterviewId") Long fullInterviewId, @RequestParam("step") Integer step) {
        boolean update = fullProcessInterviewService.lambdaUpdate()
                .set(FullProcessInterview::getStep, step)
                .eq(FullProcessInterview::getId, fullInterviewId)
                .update();
        return ResultUtils.success(update);
    }

    /**
     * 生成全流程面试
     *
     * @param request
     * @return 全流程面试id
     */
    @GetMapping("/generate")
    public BaseResponse<Long> generateFullProcessInterview(HttpServletRequest request) {
        Long userId = userService.getLoginUser(request).getId();
        //生成全流程面试数据
        FullProcessInterview fullProcessInterview = new FullProcessInterview();
        fullProcessInterview.setStep(0);
        fullProcessInterview.setUserId(userId);
        fullProcessInterviewService.save(fullProcessInterview);
        //生成全流程面试分析数据
        FullProcessAnalyzeResult fullProcessAnalyzeResult = new FullProcessAnalyzeResult();
        fullProcessAnalyzeResult.setFullInterviewId(fullProcessInterview.getId());
        fullProcessAnalyzeResultService.save(fullProcessAnalyzeResult);
        return ResultUtils.success(fullProcessInterview.getId());
    }

    /**
     * 简历上传
     *
     * @param multipartFile 简历文件数据
     * @param request
     * @return
     */
    @PostMapping("/upload")
    @AuthCheck(mustRole = UserConstant.DEFAULT_ROLE)
    public BaseResponse<Long> uploadResume(@RequestPart("file") MultipartFile multipartFile, UploadFileRequest uploadFileRequest, HttpServletRequest request) {
        Long fullInterviewId = uploadFileRequest.getFullInterviewId();
        Long companyId = uploadFileRequest.getCompanyId();
        String company = companyService.getById(companyId).getName();
        Position position = positionService.lambdaQuery()
                .eq(Position::getId, uploadFileRequest.getPositionId())
                .eq(Position::getTechFieldId, uploadFileRequest.getTechFieldId())
                .one();

        //保存面试公司，技术领域，岗位信息
        fullProcessInterviewService.lambdaUpdate()
                .eq(FullProcessInterview::getId, fullInterviewId)
                .set(FullProcessInterview::getCompany, company)
                .set(FullProcessInterview::getTechFieldId, uploadFileRequest.getTechFieldId())
                .set(FullProcessInterview::getPositionId, uploadFileRequest.getPositionId())
                .set(FullProcessInterview::getPosition, position.getName())
                .set(FullProcessInterview::getTechField, position.getTechFieldName())
                .update();
        //上传简历(提取简历信息和分析简历)
        Long resumeId = resumeService.uploadFile(multipartFile, uploadFileRequest, request, true, fullInterviewId);
        //返回简历id
        return ResultUtils.success(resumeId);
    }

    /**
     * 查看简历分析状态并且查看是否通过
     *
     * @param resumeId
     * @return
     */
    @GetMapping("/check/resumeAnalyzeStatus/judge")
    public BaseResponse<Boolean> checkResumeAnalyzeStatusAndJudge(@RequestParam("resumeId") Long resumeId) throws InterruptedException {
        long start = System.currentTimeMillis();
        long timeout = 3 * 60 * 1000; //3分钟
        while (System.currentTimeMillis() - start < timeout) {
            Resume resume = resumeService.getById(resumeId);
            Integer resumeStatus = resume.getResumeStatus();
            if (resumeStatus.equals(AnalyzeStatusEnum.COMPLETED.getValue())) {
                //查看是否通过
                ResumeAnalysisResult resumeAnalysisResult = resumeAnalysisResultService.lambdaQuery()
                        .eq(ResumeAnalysisResult::getResumeId, resumeId)
                        .one();
                Integer totalScore = resumeAnalysisResult.getTotalScore();
                return ResultUtils.success(totalScore >= 60);
            } else {
                Thread.sleep(1000);
            }
        }
        //简历筛选时间超时
        return ResultUtils.success(false);
    }

    /**
     * 生成笔试题目
     *
     * @param examGenerateRequest
     * @param request
     * @return
     */
    @PostMapping("/generate/exam")
    @AuthCheck(mustRole = UserConstant.DEFAULT_ROLE)
    public BaseResponse<Long> generateExamWithFull(@RequestBody ExamGenerateRequest examGenerateRequest, HttpServletRequest request) {
        try {
            Long techFieldId = examGenerateRequest.getTechFieldId();
            Long positionId = examGenerateRequest.getPositionId();
            Long companyId = examGenerateRequest.getCompanyId();
            Long fullProcessInterviewId = examGenerateRequest.getFullProcessInterviewId();
            // 调用智能体生成笔试题
            Long examId = examService.generateExam(techFieldId, positionId, companyId, request, true, fullProcessInterviewId);
            return ResultUtils.success(examId);
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "全流程面试生成笔试题失败");
        }
    }

    /**
     * 查看笔试分析状态并且查看是否通过
     *
     * @param fullInterviewId
     * @return
     */
    @GetMapping("/check/examAnalyzeStatus/judge")
    public BaseResponse<Boolean> checkExamAnalyzeStatusAndJudge(@RequestParam("fullInterviewId") Long fullInterviewId) throws InterruptedException {
        long start = System.currentTimeMillis();
        long timeout = 3 * 60 * 1000; //3分钟
        while (System.currentTimeMillis() - start < timeout) {
            FullProcessInterview fullProcessInterview = fullProcessInterviewService.getById(fullInterviewId);
            //获取笔试id
            Long examId = fullProcessInterview.getExamId();
            Exam exam = examService.getById(examId);

            if (exam.getExamStatus().equals(AnalyzeStatusEnum.UNFINISHED.getValue())){
                //如果状态为未完成，直接就是没通过
                return ResultUtils.success(false);

            }else if (exam.getExamStatus().equals(AnalyzeStatusEnum.COMPLETED.getValue())) {
                //查看笔试是否通过
                ExamAnalysisResult examAnalysisResult = examAnalysisResultService.lambdaQuery()
                        .eq(ExamAnalysisResult::getExamId, examId)
                        .one();
                //todo 判断是否通过
                return ResultUtils.success(examAnalysisResult.getTotalScores() >= 2);
            } else {
                Thread.sleep(1000);
            }
        }
        //笔试分析时间超时
        return ResultUtils.success(false);
    }

    /**
     * 生成技术面试记录
     *
     * @param interviewGenerateRequest
     * @param request
     * @return 返回技术面试id
     */
    @PostMapping("/generate/tec/interview")
    @AuthCheck(mustRole = UserConstant.DEFAULT_ROLE)
    public BaseResponse<Long> generateTecInterviewWithFull(@RequestBody InterviewGenerateRequest interviewGenerateRequest, HttpServletRequest request) {
        try {
            Long userId = userService.getLoginUser(request).getId();
            Position position = positionService.getById(interviewGenerateRequest.getPositionId());
            String positionName = position.getName();
            String techFieldName = position.getTechFieldName();
            Long companyId = interviewGenerateRequest.getCompanyId();
            Long resumeId = interviewGenerateRequest.getResumeId();
            String interviewerGender = interviewGenerateRequest.getInterviewerGender();
            String languageMode = interviewGenerateRequest.getLanguageMode();
            Long fullInterviewId = interviewGenerateRequest.getFullInterviewId();
            String interviewerType = interviewGenerateRequest.getInterviewerType();

            Long aiInterviewId = aiInterviewService.generateTecInterview(userId, position, positionName, techFieldName, companyId, resumeId, interviewerGender, languageMode, interviewerType,true, fullInterviewId);

            return ResultUtils.success(aiInterviewId);
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "全流程面试生成技术面失败");
        }
    }


    /**
     * 查看技术结果面试分析状态并且查看是否通过
     *
     * @param fullInterviewId
     * @return
     */
    @GetMapping("/check/tecInterviewAnalyzeStatus/judge")
    public BaseResponse<Boolean> checkTecInterviewAnalyzeStatusAndJudge(@RequestParam("fullInterviewId") Long fullInterviewId) throws InterruptedException {
        long start = System.currentTimeMillis();
        long timeout = 3 * 60 * 1000;//3分钟
        while (System.currentTimeMillis() - start < timeout) {
            FullProcessInterview fullProcessInterview = fullProcessInterviewService.getById(fullInterviewId);
            //获取技术面试id
            Long aiInterviewId = fullProcessInterview.getAiInterviewId();
            //查看状态
            AiInterview aiInterview = aiInterviewService.getById(aiInterviewId);
            if (aiInterview.getInterviewStatus().equals(AnalyzeStatusEnum.UNFINISHED.getValue())) {
                //如果状态为未完成，直接就是没通过
                return ResultUtils.success(false);

            } else if (aiInterview.getInterviewStatus().equals(AnalyzeStatusEnum.COMPLETED.getValue())) {
                //查看技术面试是否通过
                AiInterviewAnalyzeResult aiInterviewAnalyzeResult = aiInterviewAnalyzeResultService.lambdaQuery()
                        .eq(AiInterviewAnalyzeResult::getAiInterviewId, aiInterviewId)
                        .one();
                //todo 判断是否通过

                return ResultUtils.success(true);
            }else {
                Thread.sleep(1000);
            }
        }
        //技术面试分析时间超时
        return ResultUtils.success(false);
    }

    /**
     * 生成HR面试记录
     *
     * @param interviewGenerateRequest
     * @param request
     * @return 返回技术面试id
     */
    @PostMapping("/generate/hr/interview")
    @AuthCheck(mustRole = UserConstant.DEFAULT_ROLE)
    public BaseResponse<Long> generateHrInterviewWithFull(@RequestBody InterviewGenerateRequest interviewGenerateRequest, HttpServletRequest request) {
        try {
            Long userId = userService.getLoginUser(request).getId();
            Position position = positionService.getById(interviewGenerateRequest.getPositionId());
            String positionName = position.getName();
            String techFieldName = position.getTechFieldName();
            Long companyId = interviewGenerateRequest.getCompanyId();
            Long resumeId = interviewGenerateRequest.getResumeId();
            String interviewerGender = interviewGenerateRequest.getInterviewerGender();
            String interviewerType = interviewGenerateRequest.getInterviewerType();
            String languageMode = interviewGenerateRequest.getLanguageMode();
            Long fullInterviewId = interviewGenerateRequest.getFullInterviewId();

            //生成hr面试记录
            Long hrInterviewId = hrInterviewService.generateHrInterview(userId, position, positionName, techFieldName, companyId, resumeId, interviewerGender, languageMode, interviewerType, true, fullInterviewId);

            return ResultUtils.success(hrInterviewId);
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "全流程面试生成hr面试失败");
        }
    }


    /**
     * 查看Hr结果面试分析状态并且查看是否通过
     *
     * @param fullInterviewId
     * @return
     */
    @GetMapping("/check/hrInterviewAnalyzeStatus/judge")
    public BaseResponse<Boolean> checkHrInterviewAnalyzeStatusAndJudge(@RequestParam("fullInterviewId") Long fullInterviewId) throws InterruptedException {
        long start = System.currentTimeMillis();
        long timeout = 3 * 60 * 1000;//3分钟
        while (System.currentTimeMillis() - start < timeout) {
            FullProcessInterview fullProcessInterview = fullProcessInterviewService.getById(fullInterviewId);
            //获取技术面试id
            Long hrInterviewId = fullProcessInterview.getHrInterviewId();
            HrInterview hrInterview = hrInterviewService.getById(hrInterviewId);
            //查看状态
            if(hrInterview.getInterviewStatus().equals(AnalyzeStatusEnum.UNFINISHED.getValue())){
                //如果状态为未完成，直接就是没通过
                return ResultUtils.success(false);
            }else if(hrInterview.getInterviewStatus().equals(AnalyzeStatusEnum.COMPLETED.getValue())) {
                //查看技术面试是否通过
                HrInterviewAnalyzeResult hrInterviewAnalyzeResult = hrInterviewAnalyzeResultService.lambdaQuery()
                        .eq(HrInterviewAnalyzeResult::getHrInterviewId, hrInterviewId)
                        .one();
                //todo 判断是否通过
                return ResultUtils.success(true);
            } else {
                Thread.sleep(1000);
            }
        }
        //技术面试分析时间超时
        return ResultUtils.success(false);
    }

    /**
     * 全流程面试分析
     * @param fullProcessInterviewId
     * @return 全流程面试id
     * @throws Exception
     */
    @GetMapping("/analyze")
    public BaseResponse<Boolean> analyzeFullProcessInterviewAnalyze(@RequestParam("fullProcessInterviewId") Long fullProcessInterviewId, HttpServletRequest request){
        Boolean save = fullProcessInterviewService.analyzeFullProcessInterviewAnalyze(fullProcessInterviewId, request);
        return ResultUtils.success(save);
    }

    /**
     * 获取全流程面试分析结果
     * @param fullProcessInterviewId 全流程面试id
     * @return
     */
    @GetMapping("/get/analyze/result")
    public BaseResponse<GetFullProcessInterviewAnalyzeResultResponse> getFullProcessInterviewAnalyzeResult(@RequestParam("fullProcessInterviewId") Long fullProcessInterviewId){
        // 查询全流程面试记录
        FullProcessInterview fullProcessInterview = fullProcessInterviewService.getById(fullProcessInterviewId);

        // 查询全流程分析中间表
        FullProcessAnalyzeResult fullProcessAnalyzeResult = fullProcessAnalyzeResultService.lambdaQuery()
                .eq(FullProcessAnalyzeResult::getFullInterviewId, fullProcessInterviewId)
                .select(FullProcessAnalyzeResult::getFinalAnalysisId)
                .one();

        // 查询全流程分析报告
        FullProcessInterviewAnalyzeResult fullProcessInterviewAnalyzeResult = fullProcessInterviewAnalyzeResultService.getById(fullProcessAnalyzeResult.getFinalAnalysisId());

        //拷贝对象
        GetFullProcessInterviewAnalyzeResultResponse getFullProcessInterviewAnalyzeResultResponse = BeanUtil.copyProperties(fullProcessInterviewAnalyzeResult, GetFullProcessInterviewAnalyzeResultResponse.class);
        getFullProcessInterviewAnalyzeResultResponse.setResumeId(fullProcessInterview.getResumeId());
        getFullProcessInterviewAnalyzeResultResponse.setExamId(fullProcessInterview.getExamId());
        getFullProcessInterviewAnalyzeResultResponse.setAiInterviewId(fullProcessInterview.getAiInterviewId());
        getFullProcessInterviewAnalyzeResultResponse.setHrInterviewId(fullProcessInterview.getHrInterviewId());

        return ResultUtils.success(getFullProcessInterviewAnalyzeResultResponse);
    }

    /**
     * 获取用户全流程面试列表
     * @param request
     * @return
     */
    @GetMapping ("/user/list")
    @AuthCheck(mustRole = UserConstant.DEFAULT_ROLE)
    public BaseResponse<List<FullProcessInterview>> getFullProcessInterviewList(HttpServletRequest request) {
        Long userId = userService.getLoginUser(request).getId();
        List<FullProcessInterview> fullProcessInterviewList = fullProcessInterviewService.lambdaQuery()
                .eq(FullProcessInterview::getUserId, userId)
                .orderByDesc(FullProcessInterview::getCreateTime)
                .list();
        return  ResultUtils.success(fullProcessInterviewList);
    }

    /**
     * 删除全流程面试记录
     * @param fullProcessInterviewId
     * @param request
     * @return
     */
    @GetMapping("/delete")
    @AuthCheck(mustRole = UserConstant.DEFAULT_ROLE)
    public BaseResponse<Boolean> deleteFullProcessInterview(@RequestParam(value = "fullProcessInterviewId") Long fullProcessInterviewId, HttpServletRequest request) {
        //删除全流程面试记录和相关信息
        boolean b = fullProcessInterviewService.deleteFullProcessInterview(fullProcessInterviewId, request);
        return ResultUtils.success(b);
    }
}
